﻿#include "Config.h"

QVariant Config::GetValue(const QString &key, const QVariant &defaultValue) const
{
    return m_ConfigMap.value(key, defaultValue);
}

void Config::SetValue(const QString &key, const QVariant &value)
{
    m_ConfigMap[key] = value;
}

QMap<QString, QVariant> Config::GetConfigMap()
{
    return m_ConfigMap;
}

void ConfigWriter::WriteConfigToFile(const QString &filePath,Config &config)
{
    QMutex mutex; // 创建互斥锁
    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
    {
        QTextStream stream(&file);
        stream.setCodec("UTF-8"); // 设置编码为UTF-8
        for (auto it = config.GetConfigMap().begin(); it != config.GetConfigMap().end(); ++it)
        {
            stream << it.key() << "=" << it.value().toString() << "\n";
        }
        file.close();
    }
    mutex.unlock(); // 解锁
}

Config ConfigWriter::ReadConfigFromFile(const QString &filePath)
{
    QMutex mutex; // 创建互斥锁
    Config config;
    QFile file(filePath);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream stream(&file);
        while (!stream.atEnd()) {
            QString line = stream.readLine();
            QStringList parts = line.split("=");
            if (parts.length() == 2) {
                config.SetValue(parts[0], QVariant(parts[1]));
            }
        }
        file.close();
    }
    mutex.unlock(); // 解锁
    return config;
}
